package org.vacoor.xqq.sound;

import javax.media.*;
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * User: vacoor
 */
public abstract class AudioPlayer {

    private AudioPlayer() {
    }

    /**
     * 请使用 {@link #play(java.net.URL)} 替代该方法
     * <p/>
     * 该方法使用 {@link javax.sound.sampled.AudioSystem} 播放 wav,
     * 但是 某些编码的 wav 无法播放 (eg: Microsoft ADPCM)
     *
     * @param url
     */
    @Deprecated
    public static void playWav(final URL url) {
        new Thread() {
            public void run() {
                AudioInputStream audioInputStream = null;
                try {
                    audioInputStream = AudioSystem.getAudioInputStream(url);
                } catch (Exception e) {
                    e.printStackTrace();
                    play(url);
                    return;
                }

                AudioFormat format = audioInputStream.getFormat();
                SourceDataLine auline = null;
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

                try {
                    auline = (SourceDataLine) AudioSystem.getLine(info);
                    auline.open(format);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

                auline.start();

                try {
                    int len = 0;
                    byte[] buffer = new byte[8 * 1024 * 64];

                    while (-1 != (len = audioInputStream.read(buffer))) {
                        auline.write(buffer, 0, len);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                } finally {
                    auline.drain();
                    auline.close();
                }
            }
        }.start();
    }

    public static void play(URL url) {
        Player player = null;
        try {
            player = Manager.createPlayer(url);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        final Player p = player;
        player.addControllerListener(new ControllerAdapter() {
            @Override
            public void stop(StopEvent e) {
                super.stop(e);
                p.close();
            }

            @Override
            public void controllerError(ControllerErrorEvent e) {
                p.close();
            }
        });

        // 这里本来就是多线程, 不需再创建线程
        player.start();
    }

    /*
        String driver = "vfw:Logitech USB Video Camera:0";
        String driver = "vfw:Microsoft WDM Image Capture (Win32):0";
        CaptureDeviceInfo device = CaptureDeviceManager.getDevice(driver);
        Vector<CaptureDeviceInfo> deviceList = CaptureDeviceManager.getDeviceList(null);
        device.getLocator();
        V4L4J
     */
}
